package com.cx.base.day19_thread;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @Author: robert.song
 * @Date: Created in 2021/11/26
 */
public class Thread_13_5_原子性_原子数组 {
    public static void main(String[] args) throws InterruptedException {
        demo(() -> new int[10], array -> array.length, (array, index) -> array[index]++, array -> System.out.println(Arrays.toString(array)));
        demo(() -> new AtomicIntegerArray(10), (array) -> array.length(), (array, index) -> array.getAndIncrement(index), array -> System.out.println(array));
    }

    /**
     * @param arraySupplier 提供数组长度，可以是线程不安全数组或者线程安全数组
     * @param lengthFun     获取数组长度的方法
     * @param putConsumer   自增方法，回传array,index
     * @param printConsumer 打印数组的方法
     * @param <T>
     */
    private static <T> void demo(Supplier<T> arraySupplier, Function<T, Integer> lengthFun, BiConsumer<T, Integer> putConsumer, Consumer<T> printConsumer) throws InterruptedException {
        List<Thread> ts = new ArrayList<>();
        T array = arraySupplier.get();
        int length = lengthFun.apply(array);
        for (int i = 0; i < length; i++) {
//            每个线程对数组作1000次操作
            ts.add(new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    putConsumer.accept(array, j % length);
                }
            }));
        }
        ts.forEach(t -> {
            t.start();
        });
        Thread.sleep(1000);
        printConsumer.accept(array);

    }
}
